package org.hy.framework.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//import org.hibernate.service.ServiceRegistry;
//import org.hibernate.service.ServiceRegistryBuilder;

public class Hibernate3Util {
	//private final static SessionFactory FACTORY = buildSessionFactory();
	private  static SessionFactory sessionFactory = null;
	
	public static SessionFactory buildSessionFactory( String resource) {
		//默认路径是/hibernate.cfg.xml
		Configuration cfg = new Configuration().configure(resource);
		//Hibernante4
		//ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		//SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
		
		//Hibernante3
		sessionFactory = cfg.buildSessionFactory();
		return sessionFactory;
	}

	public static SessionFactory buildSessionFactory() {
		Configuration cfg = new Configuration().configure();
		//Hibernante4
		//ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		//SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
		
		//Hibernante3
		sessionFactory = cfg.buildSessionFactory();
		return sessionFactory;
	}
	
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	/**
	 * 
	 * 
	 * <ul>
	 * <li>方法含义：不用进行session.close();操作</li>
	 * <li>方法作者：花宏宇</li>
	 * <li>编写日期：2013-3-17；时间：下午5:37:04</li>
	 * </ul>
	 * <ul>
	 * <b>修订编号：</b>
	 * <li>修订日期：</li>
	 * <li>修订作者：</li>
	 * <li>修订原因：</li>
	 * <li>修订内容：</li>
	 * </ul>
	 * @return
	 * @return
	 */
	public static Session getCurrentSession() {
		if (sessionFactory == null) {
			sessionFactory = buildSessionFactory();
		} 
		return  sessionFactory.getCurrentSession();
	}
	
	
	public static Session openSession() {
		if (sessionFactory == null) {
			sessionFactory = buildSessionFactory();
		} 
		return sessionFactory.openSession();
	}
	
	public static void close(Session session) {
		if(session!=null) session.close();
	}
}
